<script setup>
import {computed, onMounted, ref, watch, provide} from 'vue'
import SonItem from './components/SonItem.vue'
import Model from './components/Model.vue'
import {useChannelStore} from '@/store/channel.js'

// computed用法
const count = ref(1)
const plusOne = computed({
  get: () => count.value + 1,
  set: (value) => {
    count.value = value - 1
  }
})
plusOne.value = 1
console.log(count.value) // 0
console.log(plusOne.value) // 1

// watch用法
const name = ref('zs')
const age = ref(13)
watch(age, (newVal) => {
  console.log(`监听到了年龄新值${newVal}`)
})
watch(name, (newVal) => {
  console.log(`监听到了名字新值${newVal}`)
})
const plusAgeFn = (value) => {
  age.value = value
}
const changeNameFn = (value) => {
  name.value = value
}

// 模板引用
const inp = ref(null)
// 操作dom元素必须在Mounted里面
onMounted(() => {
  inp.value.focus()
})

// 使用子组件中的方法或者变量（在子组件当中必须暴露出来）
const son = ref(null)
onMounted(() => {
  son.value.plusAge()
})

// provide 和 inject
const num = ref(0)
provide('f-num', num)
setTimeout(() => {
  num.value = 1
}, 2000)
// 子组件不能修改父组件传过去的值，但是可以提供一个方法让子组件接收后修改
provide('update-num', newVal => {
  num.value = newVal
})

// defineModel  实现父和子的双向绑定
const inputNum = ref(12345)

// 使用pinia
const channelStore = useChannelStore()
</script>

<template>
  <div class="father">我是父亲组件 --- 名字是{{ name }} -- 年龄是{{ age }}</div>
  <div>
    <SonItem :name="name" :age="age" @plusAge="plusAgeFn" @changeName="changeNameFn" ref="son"></SonItem>
  </div>
  <hr>
  <div>
    <input class="input" ref="inp">
  </div>
  <hr>
  <div>
    <Model v-model="inputNum"></Model>
    {{inputNum}}
  </div>

  <hr>
  <div>
    <button @click="channelStore.getChannelList">获取channel数据</button>
    <ul>
      <li v-for="item in channelStore.channelList" :key="item.id">{{item.name}}</li>
    </ul>
  </div>
</template>

<style scoped>
.father {
  width: 100px;
  height: 100px;
  background-color: rebeccapurple;
}
</style>
